//
//  PublicMethod.m
//  PlamBaida
//
//  Created by zp on 13-4-22.
//  Copyright (c) 2013年 zp. All rights reserved.
//

#import "PublicMethod.h"
#import "AppDelegate.h"
#import "DataSaveAndGet.h"
#import "SSKeychain.h"
#include <sys/types.h>
#include <sys/sysctl.h>
#import "SendViewController.h"
#import "ReceiveViewController.h"
#import "MineViewContrller.h"

@implementation PublicMethod

//货主版进入新主页，token失效时
+(void)enterNewMain{

    NSLog(@"enternew");
    
    AppDelegate * appdele = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    
    appdele.tabbarcontr = [[UITabBarController alloc]init];
    
    appdele.window = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
    
    appdele.window.backgroundColor = [UIColor whiteColor];
    
    
//    SendViewController * sendvc = [[SendViewController alloc]init];
//    
//    ReceiveViewController * receivevc = [[ReceiveViewController alloc]init];
//    
//    MineViewContrller * minevc = [[MineViewContrller alloc]init];
//    
//    
//    UINavigationController * navsend = [[UINavigationController alloc]initWithRootViewController:sendvc];
//    
//    UINavigationController * navreceive = [[UINavigationController alloc]initWithRootViewController:receivevc];
//    
//    UINavigationController * navmine = [[UINavigationController alloc]initWithRootViewController:minevc];
//    
//    UIImage * image1 = [[UIImage imageNamed:@"fahuo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    UIImage * image1_in = [[UIImage imageNamed:@"fahuo_in.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    UIImage * image2 = [[UIImage imageNamed:@"daohuo.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    UIImage * image2_in = [[UIImage imageNamed:@"daohuo_in.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    UIImage * image3 = [[UIImage imageNamed:@"mine.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    UIImage * image3_in = [[UIImage imageNamed:@"mine_in.png"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//    
//    UITabBarItem * mainitem = [[UITabBarItem alloc]initWithTitle:@"发货" image:image1 selectedImage:image1_in];
//    
//    UITabBarItem * receiveitem = [[UITabBarItem alloc]initWithTitle:@"到货" image:image2 selectedImage:image2_in];
//    
//    UITabBarItem * mineitem = [[UITabBarItem alloc]initWithTitle:@"我的" image:image3 selectedImage:image3_in];
//    
//    navmine.tabBarItem = mineitem;
//    
//    navsend.tabBarItem = mainitem;
//    
//    navreceive.tabBarItem = receiveitem;
//    
//    appdele.tabbarcontr = [[UITabBarController alloc]init];
//    
//    appdele.tabbarcontr.tabBar.barTintColor = COLORRGBA(7, 24, 57, 1);
//    
//    appdele.tabbarcontr.viewControllers = @[navsend,navreceive,navmine];
//    
//    appdele.window.rootViewController = appdele.tabbarcontr;
//    
//    [appdele.window makeKeyAndVisible];

    appdele.minevc = [[MineViewContrller alloc]init];
    
    UINavigationController * navmine = [[UINavigationController alloc]initWithRootViewController:appdele.minevc];

    appdele.tabbarcontr = [[UITabBarController alloc]init];
    
    appdele.tabbarcontr.tabBar.barTintColor = COLORRGBA(7, 24, 57, 1);
    
    appdele.tabbarcontr.viewControllers = @[navmine];
    
    appdele.window.rootViewController = appdele.tabbarcontr;
    
    [appdele.window makeKeyAndVisible];


}
//加载loading动画.

+(UIImageView *)startAnimation{

    UIImageView *gifImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_W*0.5 - 30.0/W_BASE*SCREEN_W, SCREEN_H*0.5- 30.0/H_BASE*SCREEN_H, 60.0/W_BASE*SCREEN_W, 60.0/W_BASE*SCREEN_W)];
    
    NSArray *gifArray = [NSArray arrayWithObjects:
                         [UIImage imageNamed:@"loading_1.png"],
                         [UIImage imageNamed:@"loading_2.png"],
                         [UIImage imageNamed:@"loading_3.png"],
                         [UIImage imageNamed:@"loading_4.png"],
                         [UIImage imageNamed:@"loading_5.png"],
                         [UIImage imageNamed:@"loading_6.png"],
                         [UIImage imageNamed:@"loading_7.png"],
                         [UIImage imageNamed:@"loading_8.png"],nil];
    
    gifImageView.animationImages = gifArray; //动画图片数组
    gifImageView.animationDuration = 3; //执行一次完整动画所需的时长
    gifImageView.animationRepeatCount = 0.3;  //动画重复次数
    [gifImageView startAnimating]; //开始动画

    [WINDOW addSubview:gifImageView];


    return gifImageView;
    
}


//获取手机名
+(NSString *)getDeviceName
{
    NSString *deviceName = [UIDevice currentDevice].name;
    
    NSLog(@"设备名称：%@",deviceName);
    
    return deviceName;
}

//获取手机型号
+(NSString *)getDevicePlatform
{
    //手机型号
    size_t size;
    
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    
    char *machine = (char*)malloc(size);
    
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSUTF8StringEncoding];
    
    NSString *devicePlatform = [self devicePlatform:platform];
    
    NSLog(@"手机型号：%@",devicePlatform);
    
    return devicePlatform;
}

//设备判断
+ (NSString *)devicePlatform:(NSString *)platform
{
    /*
     iphone1,1 ( iphone )
     
     iphone1,2 ( iphone3G )
     　　
     iPhone2,1 ( 3GS 产品型号：国行-A1325 ；国际版-A1303)
     
     iPhone3,1 ( IPHONE4 GSM 产品型号：A1332  )
     
     iPhone3,2 ( IPHONE4 8G新制程版,目前新出的国行8G版均为此型号 型号同为: A1332)
     
     iPhone3,3 ( IPHONE4 CDMA 产品型号：A1349 )
     
     iPhone4,1 ( IPHONE4S 产品型号：A1387(电信版&国际版) ； A1431(联通专用型号) )
     
     iPhone5,1 ( IPHONE5 产品型号: A1428 - 3G+4G+GSM )
     
     iPhone5,2 ( IPHONE5 产品型号: A1429 ；中国电信定制版-A1442 - 3G+4G+GSM+CDMA )
     
     iPhone5,3 ( iPhone5c 产品型号: A1532 A1456 CDMA)
     
     iPhone5,4 ( iPhone5c 产品型号: A1526 A1529 A1507 GSM)
     
     iPhone6,1 ( iPhone5s 产品型号: A1533 A1453 CDMA)
     
     iPhone6,2 ( iPhone5s 产品型号: A1528 A1530 A1457 GSM)
     
     iPhone7,1 ( iPhone 6 Plus 产品型号: A1522 A1524)
     
     iPhone7,2 ( iPhone 6 产品型号: A1549 A1586)
     
     　
     
     　　ipad 1,1	　　　 ipad 1
     　　ipad 2,1	　　　 ipad 2(Wifi)
     　　ipad 2,2	　　　 ipad 2(GSM)
     　　ipad 2,3	　　　 ipad 2(CDMA)
     　　ipad 2,4	　　　 ipad 2(32nm)
     　　ipad 2,5	　　　 ipad mini(Wifi)
     　　ipad 2,6	　　　 ipad mini(GSM)
     　　ipad 2,7	　　　 ipad mini(CDMA)
     　　ipad 3,1	　　　 ipad 3(Wifi)
     　　ipad 3,2	　　　 ipad 3(CDMA)
     　　ipad 3,3	　　　 ipad 3(4G)
     　　ipad 3,4　　　  ipad 4(Wifi)
     　　ipad 3,5　　　  ipad 4(4G)
     　　ipad 3,6　　　  ipad 4(CDMA)
     
     
     　　ipod 5,1　　　  ipod touch 5
     　　ipod 4,1　　　  ipod touch 4
     　　ipod 3,1	　　　 ipod touch 3
     　　ipod 2,1	　　　 ipod touch 2
     　　ipod 1,1	　　　 ipod touch
     */
    //iPhone 2G (A1203)
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone 2G";
    //iPhone 3G (A1241/A1324)
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone 3G";
    //iPhone 3GS (A1303/A1325)
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone 3GS";
    //iPhone 4 (A1332)
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone 4";
    //iPhone 4 (A1332)
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone 4";
    //iPhone 4 (A1349)
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone 4";
    //iPhone 4S (A1387/A1431)
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone 4S";
    //iPhone 5 (A1428)
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone 5";
    //iPhone 5 (A1429/A1442)
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone 5";
    //iPhone 5c (A1456/A1532)
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone 5c";
    //iPhone 5c (A1507/A1516/A1526/A1529)
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone 5c";
    //iPhone 5s (A1453/A1533)
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone 5s";
    //iPhone 5s (A1457/A1518/A1528/A1530)
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone 5s";
    //iPhone 6 Plus (A1522/A1524)
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone 6 Plus";
    //iPhone 6 (A1549/A1586)
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone 6";
    //iPhone 6s (A1633/A1688/A1691/A1700)
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone 6s";
    //iPhone 6s Plus (A1634/A1687/A1690/A1699)
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone 6s Plus";
    
    if ([platform isEqualToString:@"iPhone8,3"]) return @"iPhoneSE";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhoneSE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone7Plus";
    
    
    //iPod Touch 1G (A1213)
    if ([platform isEqualToString:@"iPod1,1"]) return @"iPod Touch 1G";
    //iPod Touch 2G (A1288)
    if ([platform isEqualToString:@"iPod2,1"]) return @"iPod Touch 2G";
    //iPod Touch 3G (A1318)
    if ([platform isEqualToString:@"iPod3,1"]) return @"iPod Touch 3G";
    //iPod Touch 4G (A1367)
    if ([platform isEqualToString:@"iPod4,1"]) return @"iPod Touch 4G";
    //iPod Touch 5G (A1421/A1509)
    if ([platform isEqualToString:@"iPod5,1"]) return @"iPod Touch 5G";
    //iPod Touch 6G (A1574)
    if ([platform isEqualToString:@"iPod7,1"])   return @"iPod Touch 6G";
    
    
    //iPad 1G (A1219/A1337)
    if ([platform isEqualToString:@"iPad1,1"]) return @"iPad 1G";
    //iPad 2 (A1395)
    if ([platform isEqualToString:@"iPad2,1"]) return @"iPad 2";
    //iPad 2 (A1396)
    if ([platform isEqualToString:@"iPad2,2"]) return @"iPad 2";
    //iPad 2 (A1397)
    if ([platform isEqualToString:@"iPad2,3"]) return @"iPad 2";
    //iPad 2 (A1395+New Chip)
    if ([platform isEqualToString:@"iPad2,4"]) return @"iPad 2";
    //iPad Mini 1G (A1432)
    if ([platform isEqualToString:@"iPad2,5"]) return @"iPad Mini 1G";
    //iPad Mini 1G (A1454)
    if ([platform isEqualToString:@"iPad2,6"]) return @"iPad Mini 1G";
    //iPad Mini 1G (A1455)
    if ([platform isEqualToString:@"iPad2,7"]) return @"iPad Mini 1G";
    //iPad 3 (A1416)
    if ([platform isEqualToString:@"iPad3,1"]) return @"iPad 3";
    //iPad 3 (A1403)
    if ([platform isEqualToString:@"iPad3,2"]) return @"iPad 3";
    //iPad 3 (A1430)
    if ([platform isEqualToString:@"iPad3,3"]) return @"iPad 3";
    //iPad 4 (A1458)
    if ([platform isEqualToString:@"iPad3,4"]) return @"iPad 4";
    //iPad 4 (A1459)
    if ([platform isEqualToString:@"iPad3,5"]) return @"iPad 4";
    //iPad 4 (A1460)
    if ([platform isEqualToString:@"iPad3,6"]) return @"iPad 4";
    
    
    //iPad Air (A1474)
    if ([platform isEqualToString:@"iPad4,1"]) return @"iPad Air";
    //iPad Air (A1475)
    if ([platform isEqualToString:@"iPad4,2"]) return @"iPad Air";
    //iPad Air (A1476)
    if ([platform isEqualToString:@"iPad4,3"]) return @"iPad Air";
    //iPad Air 2 (A1566)
    if ([platform isEqualToString:@"iPad5,3"])   return @"iPad Air 2";
    //iPad Air 2 (A1567)
    if ([platform isEqualToString:@"iPad5,4"])   return @"iPad Air 2";
    
    
    //iPad mini 1G (A1432)
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPad mini 1G";
    //iPad mini 1G (A1454)
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPad mini 1G";
    //iPad mini 1G (A1455)
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPad mini 1G";
    //iPad Mini 2G (A1489)
    if ([platform isEqualToString:@"iPad4,4"]) return @"iPad mini 2";
    //iPad Mini 2G (A1490)
    if ([platform isEqualToString:@"iPad4,5"]) return @"iPad mini 2";
    //iPad Mini 2G (A1491)
    if ([platform isEqualToString:@"iPad4,6"]) return @"iPad mini 2";
    //iPad mini 3 (A1599)
    if ([platform isEqualToString:@"iPad4,7"])   return @"iPad mini 3";
    //iPad mini 3 (A1600)
    if ([platform isEqualToString:@"iPad4,8"])   return @"iPad mini 3";
    //iPad mini 3 (A1601)
    if ([platform isEqualToString:@"iPad4,9"])   return @"iPad mini 3";
    //iPad mini 4 (A1538)
    if ([platform isEqualToString:@"iPad5,1"])   return @"iPad mini 4";
    //iPad mini 4 (A1550)
    if ([platform isEqualToString:@"iPad5,2"])   return @"iPad mini 4";
    
    
    //iPhone Simulator
    if ([platform isEqualToString:@"i386"]) return @"iPhone Simulator";
    //iPhone Simulator
    if ([platform isEqualToString:@"x86_64"]) return @"iPhone Simulator";
    
    return @"iOS";
}

//获取设备的UUID
+ (NSString *)identifierForVendorOfUUIDString
{
    NSString *UUIDString = nil;
    
    NSDictionary *applicationInformation = [[NSBundle mainBundle] infoDictionary];
    
    NSString *keychainItemOfUUIDString = [SSKeychain passwordForService:[applicationInformation objectForKey:@"CFBundleIdentifier"] account:@"UUID"];
    
    if (keychainItemOfUUIDString.length == 0)
    {
        //获取当前的UUID
        NSString *currentUUIDString = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
        
        [SSKeychain setPassword:currentUUIDString forService:[applicationInformation objectForKey:@"CFBundleIdentifier"] account:@"UUID"];
        
        UUIDString = currentUUIDString;
    }
    else
    {
        UUIDString = keychainItemOfUUIDString;
    }
    
    NSLog(@"UUIDString = %@",UUIDString);
    
    return UUIDString;
}


//生成length长度的随机字符串
+(NSString *)getRandomStringWithLength:(NSInteger)length
{
    NSString* baseString = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString string];
    
    for (int i = 0; i < length; i++)
    {
        int x = arc4random() % baseString.length;
        
        [randomString appendFormat:@"%c",[baseString characterAtIndex:x]];
    }
    
    return randomString;
}



+ (NSString *)replaceUnicode:(NSString *)unicodeStr
{
    
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\""withString:@"\\\""];
    
    NSString *tempStr3 = [[@"\""stringByAppendingString:tempStr2]stringByAppendingString:@"\""];
    
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    
    NSString* returnStr = [ NSPropertyListSerialization  propertyListFromData:tempData
                           
                                                             mutabilityOption:NSPropertyListImmutable
                           
                                                                       format:NULL
                           
                                                             errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n"withString:@"\n"];
}


+(BOOL)isChinese:(NSString *)string
{
    //是否以中文开头(unicode中文编码范围是0x4e00~0x9fa5)
    int utfCode = 0;
    void *buffer = &utfCode;
    NSRange range = NSMakeRange(0, 1);
    //判断是不是中文开头的,buffer->获取字符的字节数据 maxLength->buffer的最大长度 usedLength->实际写入的长度，不需要的话可以传递NULL encoding->字符编码常数，不同编码方式转换后的字节长是不一样的，这里我用了UTF16 Little-Endian，maxLength为2字节，如果使用Unicode，则需要4字节 options->编码转换的选项，有两个值，分别是NSStringEncodingConversionAllowLossy和NSStringEncodingConversionExternalRepresentation range->获取的字符串中的字符范围,这里设置的第一个字符 remainingRange->建议获取的范围，可以传递NULL
    BOOL b = [string getBytes:buffer maxLength:2 usedLength:NULL encoding:NSUTF16LittleEndianStringEncoding options:NSStringEncodingConversionExternalRepresentation range:range remainingRange:NULL];
    if (b && (utfCode >= 0x4e00 && utfCode <= 0x9fa5))
        return YES;
    else
        return NO;
}

//是否首次使用新版本
+ (BOOL)checkIsFirstStartingTheNewVersionApplication
{
    NSString *currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    NSString *saveVersion = [DataSaveAndGet getValueWithType:@"NSString" withKey:APPLICATION_VERSION];
    
    BOOL isFirst = NO;
    
    if ([saveVersion isEqualToString:currentVersion])
    {
        //非首次使用新版

    }
    else
    {
        //首次使用新版本
        isFirst = YES;
    }
    
    //保存当前版本号
    [DataSaveAndGet saveValue:currentVersion withType:@"NSString" withKey:APPLICATION_VERSION];
    
    return isFirst;
}

//隐藏多余的tableview分割线
+ (void)setExtraCellLineHidden:(UITableView *)tableView
{
    UIView *view = [[UIView alloc] init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];
}


//根据图片比例和实际的高度或者宽度，获取实际的宽度或者高度
+ (float)getScaleValueWithImage:(NSString *)imageName withHeight:(float)height orWithWidth:(float)width
{
    float value = 0;
    
    UIImage *image = [UIImage imageNamed:imageName];
    
    if (height == 0)
    {
        value = image.size.height * width / image.size.width;
    }
    else
    {
        value = image.size.width * height / image.size.height;
    }
    
    return value;
}

//压缩/拉伸 图片
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    // End the context
    UIGraphicsEndImageContext();
    // Return the new image.
    return newImage;
}

//图片等比缩放
+(UIImage *) scaleImage:(UIImage *)image toScale:(float)scaleSize
{
    UIGraphicsBeginImageContext(CGSizeMake(image.size.width * scaleSize, image.size.height * scaleSize));
    [image drawInRect:CGRectMake(0, 0, image.size.width * scaleSize, image.size.height * scaleSize)];
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return scaledImage;
}



//判断字符串是否全为空格
+ (BOOL) checkStrings:(NSString*)str
{
    if([str isKindOfClass:[NSString class]])
    {
        NSMutableString *tmpStr = [NSMutableString stringWithString:str];
        NSString *space = @" ";
        NSRange range = [tmpStr rangeOfString:space];
        while (range.length != 0)
        {
            [tmpStr deleteCharactersInRange:range];
            range = [tmpStr rangeOfString:space];
        }
        if ([tmpStr length] == 0)
            return NO;
        else
            return YES;
    }
    else
    {
        return NO;
    }
}

//url中汉字转换成UTF8编码
+ (NSURL *)URLWithBaseString:(NSString *)baseString parameters:(NSDictionary *)parameters
{
    
    NSMutableString *urlString = [NSMutableString string];   //The URL starts with the base string[urlString appendString:baseString];
    
    [urlString appendString:baseString];
    
    NSString *escapedString;
    
    NSInteger keyIndex = 0;
    
    for (id key in parameters)
    {
        
        //First Parameter needs to be prefixed with a ? and any other parameter needs to be prefixed with an &
        if(keyIndex ==0)
        {
            escapedString =CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(const CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8));
            [urlString appendFormat:@"?%@=%@",key,escapedString];
            
        }
        else
        {
            escapedString =(NSString*)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)[parameters valueForKey:key], NULL, CFSTR(":/?#[]@!$&’()*+,;="), kCFStringEncodingUTF8));
            
            [urlString appendFormat:@"&%@=%@",key,escapedString];
        }
        keyIndex++;
    }
    return [NSURL URLWithString:urlString];
}

//估算字符串行高
+ (CGSize)textSizeOfString:(NSString *)text width:(CGFloat)width font:(UIFont *)font
{
    CGSize constraint = CGSizeMake(width, 20000.0f);
    
    CGSize size = [text sizeWithFont:font constrainedToSize:constraint lineBreakMode:NSLineBreakByWordWrapping];
    
    return size;
}


//图片拉伸方法
+ (UIImage *)resizeImageWithCapInsets:(UIEdgeInsets)capInsets withImage:(UIImage *)theImage
{
    CGFloat systemVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
    
    UIImage *image = nil;
    
    if (systemVersion >= 5.0)
    {
        image = [theImage resizableImageWithCapInsets:capInsets];
        return image;
    }
    image = [theImage stretchableImageWithLeftCapWidth:capInsets.left topCapHeight:capInsets.top];
    return image;
}

//拨打电话
+ (void)callPhoneNum:(NSString *)phone
{
    NSString *telURLStr = [NSString stringWithFormat:@"tel://%@",phone];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:telURLStr]];
}

//图片加载等待
+ (void)waitImageView:(UIImageView *)view withURL:(NSString *)imageHttp withPlaceholderImage:(UIImage *)placeholder
{
    int iWidth = 20;
    
    UIActivityIndicatorView *tActView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    tActView.frame=CGRectMake((view.frame.size.width-iWidth)/2, (view.frame.size.height-iWidth)/2, iWidth, iWidth);
    
    [view addSubview:tActView];
    
    
    [tActView startAnimating];
    
    NSURL *imageURL = [NSURL URLWithString:[imageHttp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    
    
    if (imageURL != nil)
    {
        [view sd_setImageWithURL:imageURL placeholderImage:placeholder completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
         {
             [tActView removeFromSuperview];
         }];
    }
    else
    {
        [view setImage:placeholder];
        [tActView removeFromSuperview];
    }
}

//图片加载等待
+ (void)waitButton:(UIButton *)button withURL:(NSString *)imageHttp withPlaceholderImage:(UIImage *)placeholderImage
{
    int iWidth = 20;
    
    UIActivityIndicatorView *tActView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    
    tActView.frame=CGRectMake((button.frame.size.width-iWidth)/2, (button.frame.size.height-iWidth)/2, iWidth, iWidth);
    
    [button addSubview:tActView];
    
    [tActView startAnimating];
    
    NSURL *imageURL = [NSURL URLWithString:[imageHttp stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        
    if (imageURL != nil)
    {
        [button sd_setImageWithURL:imageURL forState:UIControlStateNormal placeholderImage:placeholderImage options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
        {
            [tActView removeFromSuperview];
        }];
    }
    else
    {
        [tActView removeFromSuperview];
    }
}




//利用正则表达式验证邮箱
+ (BOOL)isValidateEmail:(NSString *)email
{
    if (email == nil)
        return NO;
    
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    
    return [emailTest evaluateWithObject:email];
}

//利用正则表达式验证手机号
+ (BOOL)isValidateTel:(NSString *)tel
{
    if (tel == nil)
        return NO;
    
    NSString *telRegex = @"^((13[0-9])|(147)|(15[^4,\\D])|(18[0-9]))\\d{8}$";
    
    NSPredicate *telTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", telRegex];
    
    return [telTest evaluateWithObject:tel];
}

//利用正则表达式验证ip
+ (BOOL)isValidateIP:(NSString *)ip
{
    if (ip == nil)
        return NO;
    
    NSString *ipRegex = @"^(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])$";
    
    NSPredicate *ipTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", ipRegex];
    
    return [ipTest evaluateWithObject:ip];
}

//16进制颜色(html颜色值)字符串转为UIColor
+(UIColor *) hexStringToColor: (NSString *) stringToConvert
{
    
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 charactersif ([cString length] < 6) return [UIColor blackColor];
    // strip 0X if it appearsif ([cString hasPrefix:@"0X"]) cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"]) cString = [cString substringFromIndex:1];
    if ([cString length] != 6) return [UIColor blackColor];
    
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f)
                           green:((float) g / 255.0f)
                            blue:((float) b / 255.0f)
                           alpha:1.0f];
}

//获取当前日期时间字符串
+(NSString *) getNowDateTimeString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *dateTimeStr = [formatter stringFromDate:[NSDate date]];
    
    return dateTimeStr;
}

//获取当前日期字符串
+(NSString *) getNowDateString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *dateStr = [formatter stringFromDate:[NSDate date]];
    
    return dateStr;
}

//获取当前时间字符串
+(NSString *) getNowTimeString
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    [formatter setDateFormat:@"HH:mm:ss"];
    
    NSString *timeStr = [formatter stringFromDate:[NSDate date]];
    
    return timeStr;
}


//字符串转化为NSDate
+(NSDate *) dateFromString:(NSString *)dateStr
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *dateTime = [formatter dateFromString:dateStr];
    
    return dateTime;
}

//把数据分类
+ (NSArray *) dealDataWithArray:(NSArray *)array
{
//    NSLog(@"array::%@",array);
    NSMutableArray *initAry = [NSMutableArray arrayWithArray:array];
    
    NSMutableArray *dataAry = [NSMutableArray array];
    
    
    while (initAry.count)
    {
        NSMutableArray *subAry = [NSMutableArray array];
        NSDictionary *dict = [initAry objectAtIndex:0];
        NSString *deptClass = [dict objectForKey:@"deptName"];
        for (int i = 0; i < initAry.count; i++)
        {
            NSDictionary *iDict = [initAry objectAtIndex:i];
            NSString *deptName = [iDict objectForKey:@"deptName"];
            if ([deptName isEqualToString:deptClass])
            {
                [subAry addObject:iDict];
            }
        }
        [dataAry addObject:subAry];
        [initAry removeObjectsInArray:subAry];
    }
    
//    NSLog(@"dataAry:::%@",dataAry);
    
    return dataAry;
}

//获取日期中的年
+ (NSInteger) yearFromDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    
    int year = (int)[comps year];
    
    return year;
}


//获取日期中的月份
+ (NSInteger) monthFromDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    
    int month = (int)[comps month];
    
    return month;
}
//获取日期中的日期
+ (NSInteger) dayFromDate:(NSDate *)date
{
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSInteger unitFlags = NSYearCalendarUnit |
    NSMonthCalendarUnit |
    NSDayCalendarUnit |
    NSWeekdayCalendarUnit |
    NSHourCalendarUnit |
    NSMinuteCalendarUnit |
    NSSecondCalendarUnit;
    
    NSDateComponents *comps = [calendar components:unitFlags fromDate:date];
    
    int day = (int)[comps day];
    
    return day;
}

//在日期date经过day天之后的日期
+ (NSString *) theDate:(NSString *)date afterDays:(NSInteger)day
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    [formatter setTimeZone:[NSTimeZone defaultTimeZone]];
    
    [formatter setDateFormat:@"yyyy-MM-dd"];
    
    NSDate *beginDate = [self dateFromString:date];
    
    NSTimeInterval interval = 60 * 60 * 24 * day;
    
    NSString *resultDateStr = [formatter stringFromDate:[beginDate initWithTimeInterval:interval sinceDate:beginDate]];
    
    return resultDateStr;
}

//是否包含中文
+ (BOOL)isIncludeChineseInString:(NSString*)str
{
    for (int i=0; i<str.length; i++)
    {
        unichar ch = [str characterAtIndex:i];
        if (0x4e00 < ch  && ch < 0x9fff)
        {
            return true;
        }
    }
    return false;
}

//URLEncoded
+ (NSString *)URLEncodedString:(NSString *)string
{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)string,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));
    
//    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%20"withString:@"+"];
//    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%3A"withString:@":"];
//    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%2F"withString:@"/"];
//    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%3F"withString:@"?"];
//    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%3D"withString:@"="];
//    encodedString = [encodedString stringByReplacingOccurrencesOfString:@"%26"withString:@"&"];
    
    
    
    return encodedString;
}

//URLDEcode
+ (NSString *)URLDecodedString:(NSString *)string;
{
    //NSString *decodedString = [encodedString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding ];
    
    NSString *decodedString  = (__bridge_transfer NSString *)CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
                                                                                                                     (__bridge CFStringRef)string,
                                                                                                                     CFSTR(""),
                                                                                                                     CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
    return decodedString;
}












@end
